package com.leyou.auth.task;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 定时任务获取token
 * 因为这个任务本身就在授权微服务中，所以自己直接生成token
 */
@Slf4j
@Component
public class AppTokenHolder {

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    private String token;

    @Autowired
    private ApplicationInfoMapper infoMapper;


    @Autowired
    private JwtProperties prop;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadTokenTask() throws InterruptedException {
        while (true){
            try {
                // 查询该服务可用的服务的id集合
                List<Long> idList = infoMapper.queryTargetIdList(prop.getApp().getId());
                // 封装载荷
                AppInfo appInfo = new AppInfo();
                appInfo.setId(prop.getApp().getId());
                appInfo.setServiceName(prop.getApp().getSecret());
                appInfo.setTargetList(idList);
                // 发起请求，申请token
                this.token = JwtUtils.generateTokenExpireInMinutes(
                        appInfo, prop.getPrivateKey(), prop.getApp().getExpire());
                log.info("【auth服务】申请token成功！");
                break;
            }catch (Exception e){
                log.info("【auth服务】申请token失败！", e);
            }
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }

    public String getToken(){
        return token;
    }
}
